using System;
using System.Collections.Generic;
using HtmlAgilityPack;
using QuickInfoBoard.Models;
using System.Text;

namespace QuickInfoBoard.Facade {
    public class ExchangeRate
    {
      public static List<ExchangeRateModel> GetExchangeRate()
        {
            String html = GetHtml();
            return parseHtml(html);
        }

        private static String GetHtml()
        {
            System.Net.WebClient webClient = new System.Net.WebClient();
            string url = @"https://www.kuaiyilicai.com/bank/rmbfx/b-citic.html";
            webClient.Encoding = Encoding.UTF8;
            string returnStr = webClient.DownloadString(url);
            return returnStr;
        }
        private static List<ExchangeRateModel> parseHtml(String html)
        {
            var htmlDoc = new HtmlDocument();
            htmlDoc.LoadHtml(html);
            var eleTable = htmlDoc.DocumentNode.SelectSingleNode("//table[@id='bank_rate_table']/tbody");
            //好像有bug,如果直接用eleTable选择tr,会选出thead中的行.但刚才明明都排除了.
            var tableDoc = new HtmlDocument();
            tableDoc.LoadHtml(eleTable.InnerHtml);
            var eleTrs = tableDoc.DocumentNode.SelectNodes("//tr");
            var ret = new List<ExchangeRateModel>();
            foreach (var e in eleTrs)
            {
                ExchangeRateModel erm = new ExchangeRateModel();
                HtmlNode cursor = e.FirstChild.NextSibling;
                erm.币种 = cursor.InnerText.Replace("&nbsp;","").Trim();
                cursor=cursor.NextSibling.NextSibling;
                erm.汇买价 = cursor.InnerText.Trim();
                cursor = cursor.NextSibling.NextSibling;
                erm.钞买价 = cursor.InnerText.Trim();
                cursor = cursor.NextSibling.NextSibling;
                erm.汇卖价 = cursor.InnerText.Trim();
                cursor = cursor.NextSibling.NextSibling;
                erm.钞卖价 = cursor.InnerText.Trim();
                cursor = cursor.NextSibling.NextSibling;
                erm.时间 = cursor.InnerText.Trim();

                erm.来源 = "中信银行";
                ret.Add(erm);
            }
            return ret;
        }
    }
}